import tkinter as tk
from tkinter import ttk, messagebox
from state_io import load_state, save_state
from network.tcp_client import TcpClient


class TcpPanel:
    def __init__(self, parent, client: TcpClient):
        self.parent = parent
        self.client = client
        self.frame = ttk.LabelFrame(parent, text="TCP客户端", padding=10)

        self._build()
        self._bind_callbacks()

    def _build(self):
        st = load_state()
        default_ip = st.get('tcp_ip', '127.0.0.1')
        default_port = int(st.get('tcp_port', 9600))
        auto_reconnect = bool(st.get('tcp_auto_reconnect', True))

        row = ttk.Frame(self.frame)
        row.pack(fill=tk.X, pady=(0, 8))
        ttk.Label(row, text='IP:').pack(side=tk.LEFT)
        self.ip_var = tk.StringVar(value=default_ip)
        self.ip_entry = ttk.Entry(row, textvariable=self.ip_var, width=16)
        self.ip_entry.pack(side=tk.LEFT, padx=(4, 12))
        ttk.Label(row, text='端口:').pack(side=tk.LEFT)
        self.port_var = tk.StringVar(value=str(default_port))
        self.port_entry = ttk.Entry(row, textvariable=self.port_var, width=8)
        self.port_entry.pack(side=tk.LEFT, padx=(4, 12))

        # 自动重连取消

        btns = ttk.Frame(self.frame)
        btns.pack(fill=tk.X)
        self.btn_connect = ttk.Button(btns, text='连接', command=self._on_connect)
        self.btn_disconnect = ttk.Button(btns, text='断开', command=self._on_disconnect)
        self.status_var = tk.StringVar(value='未连接')
        ttk.Label(btns, textvariable=self.status_var).pack(side=tk.RIGHT)
        # 连接按钮在左，断开在右
        self.btn_connect.pack(side=tk.LEFT)
        self.btn_disconnect.pack(side=tk.LEFT, padx=(6, 0))
        self._update_buttons(False)

    def _bind_callbacks(self):
        self.client.on_connected = lambda: self._set_status(True)
        self.client.on_disconnected = lambda: self._set_status(False)

        def on_error(msg: str):
            self.status_var.set(f'错误: {msg}')
        self.client.on_error = on_error

    def _update_buttons(self, connected: bool):
        self.btn_connect.config(state=tk.DISABLED if connected else tk.NORMAL)
        self.btn_disconnect.config(state=tk.NORMAL if connected else tk.DISABLED)
        # 连接时禁用IP和端口输入框，断开时启用
        self.ip_entry.config(state=tk.DISABLED if connected else tk.NORMAL)
        self.port_entry.config(state=tk.DISABLED if connected else tk.NORMAL)

    def _set_status(self, connected: bool):
        self.status_var.set('已连接' if connected else '未连接')
        self._update_buttons(connected)

    def _on_connect(self):
        try:
            ip = self.ip_var.get().strip() or '127.0.0.1'
            port = int(self.port_var.get().strip() or '9600')
            auto_rc = False
            # persist
            st = load_state()
            st['tcp_ip'] = ip
            st['tcp_port'] = port
            st['tcp_auto_reconnect'] = auto_rc
            save_state(st)
            self.client.connect(ip, port, auto_rc)
        except Exception as e:
            messagebox.showerror('连接失败', str(e))

    def _on_disconnect(self):
        try:
            self.client.disconnect()
            messagebox.showinfo('提示', 'TCP已断开')
        except Exception as e:
            messagebox.showerror('断开失败', str(e))


